package beans.socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * 一个实现了线程化的SocketClient,较简单。<BR>
 * 
 * @author Beanstao@gmail.com
 * @date 2013-10-9下午4:25:30
 * @version 1.0
 */
public class SocketClient extends Thread
{
	private Socket client = null;
	private final String ipAddress;
	private final int port;
	private BufferedWriter bw;

	public static SocketClient ME(String ipAddress, int port)
	{
		return new SocketClient(ipAddress, port);
	}

	protected SocketClient(String ipAddress, int port)
	{
		this.ipAddress = ipAddress;
		this.port = port;
	}

	/**
	 * 核心方法，向服务器端写入数据
	 * 
	 */
	public boolean write(String msg)
	{
		try
		{
			SocketAddress address = new InetSocketAddress(this.ipAddress, this.port);
			this.client = new Socket();
			this.client.connect(address, 600);
		}
		catch (Exception e)
		{
			System.out.println("SocketClient.run()" + "连接服务器获取SOCKET。异常。" + e);
		}
		OutputStream outputStream = null;
		try
		{
			outputStream = this.client.getOutputStream();
		}
		catch (Exception e)
		{
			System.out.println("SocketClient.run()" + "从服务器获取SOCKET流异常。" + e);
		}
		bw = new BufferedWriter(new OutputStreamWriter(outputStream));
		try
		{
			bw.write(msg);
			bw.flush();
		}
		catch (IOException e)
		{
			System.out.println("SocketClient.run()" + "向SOCKET流写入数据时异常。" + e);
		}

		return true;
	}

	public String read()
	{
		byte[] b = new byte[1024];
		try
		{
			this.client.getInputStream().read(b);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		try
		{
			return new String(b, "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
			return "-1";
		}
		finally
		{
			close();
		}
	}

	@Override
	public void run()
	{
		System.out.println("SocketClient.run()" + "启动一个SOCKET CLIENT线程。");
	}

	public void close()
	{
		try
		{
			bw.close();
		}
		catch (IOException e)
		{
			System.out.println("SocketClient.run()" + "关闭SOCKET流异常。" + e);
		}
		try
		{
			this.client.close();
		}
		catch (IOException e)
		{
			System.out.println("SocketClient.run()" + "关闭SOCKET CLIENT异常。" + e);
		}
		System.out.println("SocketClient.run()" + "向服务器发送消息正常，Client已关闭。");
	}

}
